package com.example.designpattern.observer;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author long
 */
public class StockExchange implements Observable{

    // 最新价格
    private double latestPrice;

    // 存储订阅者
    private CopyOnWriteArrayList<Observer> observerList;

    public StockExchange(){
        this.observerList = new CopyOnWriteArrayList<>();
    }

    @Override
    public synchronized void subscribe(Observer observer) {
        if (observer == null){
            throw new NullPointerException();
        }

        if(!observerList.contains(observer)){
            observerList.add(observer);
        }
    }

    @Override
    public synchronized void unSubscribe(Observer observer) {
        observerList.remove(observer);
    }

    @Override
    public synchronized void notifyObservers() {
        observerList.forEach(observer -> {
            observer.update(latestPrice);
        });
    }

    @Override
    public void setPrice(double newPrice) {
        if(newPrice == this.latestPrice){
            return;
        }

        this.latestPrice = newPrice;

        // 通知所有订阅者
        notifyObservers();
    }

}
